package com.leetcode.tree.recursion;

import com.leetcode.basic.TreeNode;
import com.leetcode.binary_search.FirstBadVersion_278;

import java.util.*;

/**
 * @author Dennis Li
 * @date 2020/10/16 15:42
 */
public class ZigzagLevelOrder_103 {

    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        if (root == null) return res;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        boolean isReversed = true;

        while (!queue.isEmpty()) {
            int size = queue.size();
            LinkedList<Integer> list = new LinkedList<>();
            while (size-- > 0) {
                TreeNode node = queue.poll();
                if (!isReversed) list.offerFirst(node.val);
                else list.offerLast(node.val);
                if (node.left != null) queue.offer(node.left);
                if (node.right != null) queue.offer(node.right);
            }
            res.add(list);
            isReversed = !isReversed;
        }

        return res;
    }

}
